package com.example.server.security;

import com.example.common.security.GrantedAuthority;
import com.example.common.pojo.Admin;
import com.example.common.pojo.Role;
import com.example.common.vo.RespBean;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class AnnoDrivenSessionBasedAuthorizeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {

            HandlerMethod handlerMethod = (HandlerMethod) handler;
            PreAuthorize methodAnnotation = handlerMethod.getMethodAnnotation(PreAuthorize.class);

            if (methodAnnotation != null) {

                String type = methodAnnotation.type();
                String[] roles = methodAnnotation.roles();

                // List<String>
                List<GrantedAuthority> allowedAuthorities = Arrays.asList(roles).stream()
                        .map(SimpleGrantedAuthority::new).collect(Collectors.toList());

                Admin auth = (Admin) request.getSession().getAttribute("auth");
                List<Role> hadAuthorities = auth.getRoles();

                if (type.equals("hasAnyRole")) {
                    /**
                     * 1 收集请求需要的角色范围
                     * 2 收集用户具备的角色范围
                     * 3 两者再进行比较
                     */
                    for (GrantedAuthority allowedAuthority : allowedAuthorities) {

                        for (Role hadAuthority : hadAuthorities) {

                            if (allowedAuthority.getPerm().equals(hadAuthority.getPerm())) {
                                return true;
                            }
                        }
                    }

                } else if (type.equals("hasAllRoles")) {

                    // TODO 作业
                }
                throw RespBean.AUTH_FAILED_ERROR_411.toException();
            }
        }

        return true;
    }
}
